#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
网络渗透和横向移动场景测试模块
Network Penetration and Lateral Movement Scenario Testing Module

该模块实现：
1. 网络发现和扫描场景
2. 服务枚举和漏洞识别场景
3. 横向移动场景
4. 内网渗透场景
5. 数据渗透场景
6. 网络持久化场景
"""

import os
import sys
import time
import random
import socket
import subprocess
from typing import Dict, List, Optional, Any, Tuple
from dataclasses import dataclass
from datetime import datetime, timedelta
from enum import Enum
import ipaddress

# 添加项目根目录到Python路径
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

class NetworkTestType(Enum):
    """网络测试类型"""
    DISCOVERY = "discovery"
    ENUMERATION = "enumeration"
    LATERAL_MOVEMENT = "lateral_movement"
    PRIVILEGE_ESCALATION = "privilege_escalation"
    DATA_EXFILTRATION = "data_exfiltration"
    PERSISTENCE = "persistence"

class MovementMethod(Enum):
    """横向移动方法"""
    SSH_KEY = "ssh_key"
    PASSWORD_SPRAY = "password_spray"
    HASH_PASSING = "hash_passing"
    TOKEN_IMPERSONATION = "token_impersonation"
    WMI_EXECUTION = "wmi_execution"
    PSEXEC = "psexec"
    RDP_HIJACKING = "rdp_hijacking"

@dataclass
class NetworkTarget:
    """网络目标"""
    ip_address: str
    hostname: str
    os_type: str
    open_ports: List[int]
    services: Dict[int, str]
    vulnerabilities: List[str]
    access_level: str

@dataclass
class PenetrationTest:
    """渗透测试结果"""
    test_id: str
    test_name: str
    test_type: NetworkTestType
    target_network: str
    discovered_hosts: List[NetworkTarget]
    successful_compromises: List[str]
    lateral_movements: List[Dict[str, Any]]
    data_exfiltrated: Dict[str, Any]
    persistence_methods: List[str]
    stealth_rating: float
    success_rate: float
    execution_time: float
    techniques_used: List[str]
    recommendations: List[str]

class NetworkPenetrationScenarios:
    """网络渗透场景测试器"""
    
    def __init__(self, target_network: str = "101.37.80.0/24"):
        self.target_network = target_network
        self.test_results: List[PenetrationTest] = []
        self.discovered_hosts: List[NetworkTarget] = []
        self.compromised_hosts: List[str] = []
        
    def _generate_network_targets(self, count: int = 10) -> List[NetworkTarget]:
        """生成模拟网络目标"""
        targets = []
        base_ip = "101.37.80"
        
        os_types = ["Linux", "Windows", "FreeBSD", "VMware ESXi"]
        service_map = {
            22: "SSH",
            23: "Telnet", 
            25: "SMTP",
            53: "DNS",
            80: "HTTP",
            135: "RPC",
            139: "NetBIOS",
            443: "HTTPS",
            445: "SMB",
            993: "IMAPS",
            995: "POP3S",
            3389: "RDP",
            5432: "PostgreSQL",
            3306: "MySQL"
        }
        
        vulnerabilities = [
            "CVE-2021-44228 (Log4j)",
            "CVE-2020-1472 (Zerologon)",
            "CVE-2019-0708 (BlueKeep)",
            "CVE-2017-0144 (EternalBlue)",
            "Weak SSH credentials",
            "Default passwords",
            "Unpatched services",
            "Misconfigured permissions"
        ]
        
        for i in range(count):
            ip = f"{base_ip}.{random.randint(1, 254)}"
            hostname = f"host-{random.randint(1000, 9999)}"
            os_type = random.choice(os_types)
            
            # 生成开放端口
            all_ports = list(service_map.keys())
            open_ports = random.sample(all_ports, random.randint(3, 8))
            services = {port: service_map[port] for port in open_ports}
            
            # 生成漏洞
            host_vulns = random.sample(vulnerabilities, random.randint(1, 3))
            
            target = NetworkTarget(
                ip_address=ip,
                hostname=hostname,
                os_type=os_type,
                open_ports=sorted(open_ports),
                services=services,
                vulnerabilities=host_vulns,
                access_level="none"
            )
            targets.append(target)
        
        return targets
    
    def test_network_discovery(self) -> PenetrationTest:
        """测试网络发现场景"""
        print("🔍 测试网络发现和扫描场景...")
        
        # 模拟网络发现
        discovery_techniques = [
            {"name": "ICMP扫描", "coverage": 0.95, "stealth": 0.3, "speed": 0.9},
            {"name": "TCP SYN扫描", "coverage": 0.85, "stealth": 0.6, "speed": 0.7},
            {"name": "UDP扫描", "coverage": 0.7, "stealth": 0.8, "speed": 0.5},
            {"name": "ARP扫描", "coverage": 0.9, "stealth": 0.9, "speed": 0.8},
            {"name": "被动发现", "coverage": 0.6, "stealth": 0.95, "speed": 0.3}
        ]
        
        # 生成目标主机
        total_hosts = random.randint(15, 30)
        self.discovered_hosts = self._generate_network_targets(total_hosts)
        
        # 模拟发现过程
        discovered_count = 0
        used_techniques = []
        
        for technique in discovery_techniques:
            if random.random() < 0.8:  # 80%概率使用该技术
                hosts_found = int(total_hosts * technique["coverage"] * random.uniform(0.8, 1.0))
                discovered_count = max(discovered_count, hosts_found)
                used_techniques.append(technique["name"])
                print(f"  ✅ {technique['name']}: 发现 {hosts_found} 个主机")
        
        # 计算发现率
        discovery_rate = min(discovered_count / total_hosts, 1.0)
        avg_stealth = sum(t["stealth"] for t in discovery_techniques if t["name"] in used_techniques) / len(used_techniques)
        
        test_result = PenetrationTest(
            test_id="network_discovery_001",
            test_name="网络发现和扫描测试",
            test_type=NetworkTestType.DISCOVERY,
            target_network=self.target_network,
            discovered_hosts=self.discovered_hosts[:discovered_count],
            successful_compromises=[],
            lateral_movements=[],
            data_exfiltrated={},
            persistence_methods=[],
            stealth_rating=avg_stealth,
            success_rate=discovery_rate,
            execution_time=random.uniform(30.0, 120.0),
            techniques_used=used_techniques,
            recommendations=[
                "使用多种扫描技术提高覆盖率",
                "ARP扫描在内网环境中效果最佳",
                "被动发现虽慢但隐蔽性最高",
                "结合主动和被动发现技术"
            ]
        )
        
        self.test_results.append(test_result)
        print(f"  📊 发现率: {discovery_rate:.1%}, 隐蔽性: {avg_stealth:.1%}")
        return test_result
    
    def test_service_enumeration(self) -> PenetrationTest:
        """测试服务枚举场景"""
        print("🔎 测试服务枚举和漏洞识别场景...")
        
        if not self.discovered_hosts:
            self.discovered_hosts = self._generate_network_targets(10)
        
        enumeration_results = []
        vulnerable_services = []
        
        # 模拟服务枚举
        for host in self.discovered_hosts[:10]:  # 限制测试主机数量
            host_results = {
                "ip": host.ip_address,
                "hostname": host.hostname,
                "enumerated_services": [],
                "identified_vulnerabilities": [],
                "banner_grabbed": random.random() < 0.8
            }
            
            # 枚举每个开放端口的服务
            for port in host.open_ports:
                service_name = host.services.get(port, "Unknown")
                version = f"{service_name} {random.randint(1, 5)}.{random.randint(0, 9)}"
                
                service_info = {
                    "port": port,
                    "service": service_name,
                    "version": version,
                    "vulnerable": random.random() < 0.3
                }
                
                host_results["enumerated_services"].append(service_info)
                
                if service_info["vulnerable"]:
                    vuln = random.choice(host.vulnerabilities)
                    host_results["identified_vulnerabilities"].append(vuln)
                    vulnerable_services.append(f"{host.ip_address}:{port}")
            
            enumeration_results.append(host_results)
            status = "成功" if host_results["banner_grabbed"] else "部分成功"
            print(f"  {'✅' if host_results['banner_grabbed'] else '⚠️'} 枚举 {host.ip_address}: {status}")
        
        # 计算统计信息
        total_services = sum(len(result["enumerated_services"]) for result in enumeration_results)
        total_vulnerabilities = sum(len(result["identified_vulnerabilities"]) for result in enumeration_results)
        success_rate = len([r for r in enumeration_results if r["banner_grabbed"]]) / len(enumeration_results)
        
        test_result = PenetrationTest(
            test_id="service_enum_001",
            test_name="服务枚举和漏洞识别测试",
            test_type=NetworkTestType.ENUMERATION,
            target_network=self.target_network,
            discovered_hosts=self.discovered_hosts[:10],
            successful_compromises=[],
            lateral_movements=[],
            data_exfiltrated={"enumerated_services": total_services, "vulnerabilities": total_vulnerabilities},
            persistence_methods=[],
            stealth_rating=0.7,
            success_rate=success_rate,
            execution_time=random.uniform(60.0, 300.0),
            techniques_used=[
                "端口扫描",
                "服务版本识别",
                "Banner抓取",
                "漏洞扫描",
                "默认凭据测试"
            ],
            recommendations=[
                "重点关注高危端口服务",
                "使用多种扫描工具交叉验证",
                "注意扫描频率避免触发防护",
                "优先测试已知漏洞服务"
            ]
        )
        
        self.test_results.append(test_result)
        print(f"  📊 枚举成功率: {success_rate:.1%}, 发现 {total_vulnerabilities} 个漏洞")
        return test_result
    
    def test_lateral_movement(self) -> PenetrationTest:
        """测试横向移动场景"""
        print("➡️ 测试横向移动场景...")
        
        if not self.discovered_hosts:
            self.discovered_hosts = self._generate_network_targets(8)
        
        # 模拟初始入侵点
        initial_host = random.choice(self.discovered_hosts)
        initial_host.access_level = "user"
        self.compromised_hosts = [initial_host.ip_address]
        
        movement_attempts = []
        successful_movements = []
        
        # 定义横向移动方法
        movement_methods = [
            {"method": MovementMethod.SSH_KEY, "success_rate": 0.8, "stealth": 0.9, "requirements": [22]},
            {"method": MovementMethod.PASSWORD_SPRAY, "success_rate": 0.6, "stealth": 0.4, "requirements": [22, 3389]},
            {"method": MovementMethod.HASH_PASSING, "success_rate": 0.7, "stealth": 0.8, "requirements": [445]},
            {"method": MovementMethod.WMI_EXECUTION, "success_rate": 0.75, "stealth": 0.7, "requirements": [135]},
            {"method": MovementMethod.PSEXEC, "success_rate": 0.8, "stealth": 0.6, "requirements": [445]},
            {"method": MovementMethod.RDP_HIJACKING, "success_rate": 0.5, "stealth": 0.9, "requirements": [3389]}
        ]
        
        print(f"  🎯 初始入侵点: {initial_host.ip_address} ({initial_host.hostname})")
        
        # 尝试横向移动到其他主机
        for target_host in self.discovered_hosts:
            if target_host.ip_address == initial_host.ip_address:
                continue
            
            # 选择适用的移动方法
            applicable_methods = [
                method for method in movement_methods
                if any(port in target_host.open_ports for port in method["requirements"])
            ]
            
            if not applicable_methods:
                continue
            
            chosen_method = random.choice(applicable_methods)
            success = random.random() < chosen_method["success_rate"]
            
            movement_attempt = {
                "source": initial_host.ip_address,
                "target": target_host.ip_address,
                "method": chosen_method["method"].value,
                "success": success,
                "stealth": chosen_method["stealth"],
                "execution_time": random.uniform(10.0, 60.0)
            }
            
            movement_attempts.append(movement_attempt)
            
            if success:
                target_host.access_level = "user"
                self.compromised_hosts.append(target_host.ip_address)
                successful_movements.append(movement_attempt)
                print(f"  ✅ 成功移动到 {target_host.ip_address} (方法: {chosen_method['method'].value})")
            else:
                print(f"  ❌ 移动失败 {target_host.ip_address} (方法: {chosen_method['method'].value})")
        
        # 计算统计信息
        success_rate = len(successful_movements) / len(movement_attempts) if movement_attempts else 0
        avg_stealth = sum(m["stealth"] for m in movement_attempts) / len(movement_attempts) if movement_attempts else 0
        
        test_result = PenetrationTest(
            test_id="lateral_movement_001",
            test_name="横向移动测试",
            test_type=NetworkTestType.LATERAL_MOVEMENT,
            target_network=self.target_network,
            discovered_hosts=self.discovered_hosts,
            successful_compromises=self.compromised_hosts,
            lateral_movements=successful_movements,
            data_exfiltrated={},
            persistence_methods=[],
            stealth_rating=avg_stealth,
            success_rate=success_rate,
            execution_time=sum(m["execution_time"] for m in movement_attempts),
            techniques_used=[m["method"] for m in movement_attempts],
            recommendations=[
                "SSH密钥复用是最隐蔽的移动方法",
                "密码喷洒容易被检测，谨慎使用",
                "哈希传递在Windows环境中效果好",
                "WMI执行提供良好的隐蔽性"
            ]
        )
        
        self.test_results.append(test_result)
        print(f"  📊 移动成功率: {success_rate:.1%}, 控制 {len(self.compromised_hosts)} 台主机")
        return test_result
    
    def test_privilege_escalation_network(self) -> PenetrationTest:
        """测试网络环境下的权限提升场景"""
        print("⬆️ 测试网络权限提升场景...")
        
        if not self.compromised_hosts:
            # 如果没有已控制主机，模拟一些
            self.compromised_hosts = [host.ip_address for host in self.discovered_hosts[:3]]
        
        escalation_attempts = []
        successful_escalations = []
        
        # 权限提升技术
        escalation_techniques = [
            {"name": "内核漏洞利用", "success_rate": 0.6, "stealth": 0.7, "impact": "system"},
            {"name": "服务劫持", "success_rate": 0.8, "stealth": 0.8, "impact": "system"},
            {"name": "SUID二进制利用", "success_rate": 0.7, "stealth": 0.9, "impact": "root"},
            {"name": "Sudo配置错误", "success_rate": 0.9, "stealth": 0.95, "impact": "root"},
            {"name": "定时任务劫持", "success_rate": 0.75, "stealth": 0.85, "impact": "system"},
            {"name": "DLL劫持", "success_rate": 0.65, "stealth": 0.8, "impact": "system"}
        ]
        
        # 对每个已控制主机尝试权限提升
        for host_ip in self.compromised_hosts:
            host = next((h for h in self.discovered_hosts if h.ip_address == host_ip), None)
            if not host:
                continue
            
            # 根据操作系统选择适用技术
            if host.os_type == "Windows":
                applicable_techniques = [t for t in escalation_techniques if "DLL" in t["name"] or "服务" in t["name"]]
            else:
                applicable_techniques = [t for t in escalation_techniques if "SUID" in t["name"] or "Sudo" in t["name"] or "内核" in t["name"]]
            
            if not applicable_techniques:
                applicable_techniques = escalation_techniques[:2]  # 使用通用技术
            
            chosen_technique = random.choice(applicable_techniques)
            success = random.random() < chosen_technique["success_rate"]
            
            escalation_attempt = {
                "host": host_ip,
                "technique": chosen_technique["name"],
                "success": success,
                "stealth": chosen_technique["stealth"],
                "impact": chosen_technique["impact"],
                "execution_time": random.uniform(5.0, 30.0)
            }
            
            escalation_attempts.append(escalation_attempt)
            
            if success:
                host.access_level = chosen_technique["impact"]
                successful_escalations.append(escalation_attempt)
                print(f"  ✅ {host_ip} 权限提升成功 ({chosen_technique['name']} → {chosen_technique['impact']})")
            else:
                print(f"  ❌ {host_ip} 权限提升失败 ({chosen_technique['name']})")
        
        # 计算统计信息
        success_rate = len(successful_escalations) / len(escalation_attempts) if escalation_attempts else 0
        avg_stealth = sum(e["stealth"] for e in escalation_attempts) / len(escalation_attempts) if escalation_attempts else 0
        
        test_result = PenetrationTest(
            test_id="network_privesc_001",
            test_name="网络权限提升测试",
            test_type=NetworkTestType.PRIVILEGE_ESCALATION,
            target_network=self.target_network,
            discovered_hosts=self.discovered_hosts,
            successful_compromises=[e["host"] for e in successful_escalations],
            lateral_movements=[],
            data_exfiltrated={},
            persistence_methods=[],
            stealth_rating=avg_stealth,
            success_rate=success_rate,
            execution_time=sum(e["execution_time"] for e in escalation_attempts),
            techniques_used=[e["technique"] for e in escalation_attempts],
            recommendations=[
                "Sudo配置错误是最常见且隐蔽的提权方式",
                "服务劫持在Windows环境中效果显著",
                "内核漏洞利用风险高但影响大",
                "优先寻找配置错误而非漏洞利用"
            ]
        )
        
        self.test_results.append(test_result)
        print(f"  📊 提权成功率: {success_rate:.1%}, 获得高权限主机 {len(successful_escalations)} 台")
        return test_result
    
    def test_data_exfiltration(self) -> PenetrationTest:
        """测试数据渗透场景"""
        print("📤 测试数据渗透场景...")
        
        # 模拟数据发现和渗透
        data_types = [
            {"type": "用户凭据", "size": random.randint(1, 10), "sensitivity": "high", "method": "内存转储"},
            {"type": "配置文件", "size": random.randint(5, 50), "sensitivity": "medium", "method": "文件复制"},
            {"type": "数据库备份", "size": random.randint(100, 1000), "sensitivity": "high", "method": "数据库导出"},
            {"type": "日志文件", "size": random.randint(50, 500), "sensitivity": "low", "method": "日志收集"},
            {"type": "源代码", "size": random.randint(20, 200), "sensitivity": "medium", "method": "Git克隆"},
            {"type": "证书密钥", "size": random.randint(1, 5), "sensitivity": "critical", "method": "密钥提取"}
        ]
        
        exfiltration_methods = [
            {"name": "HTTP隧道", "bandwidth": 1.0, "stealth": 0.8, "reliability": 0.9},
            {"name": "DNS隧道", "bandwidth": 0.1, "stealth": 0.95, "reliability": 0.7},
            {"name": "ICMP隧道", "bandwidth": 0.2, "stealth": 0.9, "reliability": 0.8},
            {"name": "SSH隧道", "bandwidth": 2.0, "stealth": 0.85, "reliability": 0.95},
            {"name": "邮件附件", "bandwidth": 0.5, "stealth": 0.6, "reliability": 0.8},
            {"name": "云存储", "bandwidth": 5.0, "stealth": 0.7, "reliability": 0.9}
        ]
        
        exfiltration_results = []
        total_data_size = 0
        
        # 模拟数据渗透过程
        for data in data_types:
            if random.random() < 0.7:  # 70%概率发现并尝试渗透
                method = random.choice(exfiltration_methods)
                
                # 计算传输时间（基于大小和带宽）
                transfer_time = data["size"] / method["bandwidth"]
                success = random.random() < method["reliability"]
                
                result = {
                    "data_type": data["type"],
                    "size_mb": data["size"],
                    "sensitivity": data["sensitivity"],
                    "discovery_method": data["method"],
                    "exfiltration_method": method["name"],
                    "success": success,
                    "transfer_time": transfer_time,
                    "stealth": method["stealth"]
                }
                
                exfiltration_results.append(result)
                
                if success:
                    total_data_size += data["size"]
                    print(f"  ✅ 渗透 {data['type']}: {data['size']}MB (方法: {method['name']})")
                else:
                    print(f"  ❌ 渗透失败 {data['type']} (方法: {method['name']})")
        
        # 计算统计信息
        successful_exfiltrations = [r for r in exfiltration_results if r["success"]]
        success_rate = len(successful_exfiltrations) / len(exfiltration_results) if exfiltration_results else 0
        avg_stealth = sum(r["stealth"] for r in exfiltration_results) / len(exfiltration_results) if exfiltration_results else 0
        
        test_result = PenetrationTest(
            test_id="data_exfiltration_001",
            test_name="数据渗透测试",
            test_type=NetworkTestType.DATA_EXFILTRATION,
            target_network=self.target_network,
            discovered_hosts=self.discovered_hosts,
            successful_compromises=self.compromised_hosts,
            lateral_movements=[],
            data_exfiltrated={
                "total_size_mb": total_data_size,
                "data_types": len(successful_exfiltrations),
                "methods_used": list(set(r["exfiltration_method"] for r in successful_exfiltrations))
            },
            persistence_methods=[],
            stealth_rating=avg_stealth,
            success_rate=success_rate,
            execution_time=sum(r["transfer_time"] for r in exfiltration_results),
            techniques_used=[r["exfiltration_method"] for r in exfiltration_results],
            recommendations=[
                "DNS隧道隐蔽性最高但速度慢",
                "SSH隧道平衡了速度和隐蔽性",
                "优先渗透高敏感度数据",
                "分批次小量传输避免检测"
            ]
        )
        
        self.test_results.append(test_result)
        print(f"  📊 渗透成功率: {success_rate:.1%}, 总计渗透 {total_data_size}MB 数据")
        return test_result
    
    def test_network_persistence(self) -> PenetrationTest:
        """测试网络持久化场景"""
        print("🔒 测试网络持久化场景...")
        
        # 网络持久化方法
        persistence_methods = [
            {"name": "SSH后门", "stealth": 0.9, "persistence": 0.8, "detection_difficulty": 0.85},
            {"name": "Web Shell", "stealth": 0.6, "persistence": 0.7, "detection_difficulty": 0.6},
            {"name": "DNS隧道后门", "stealth": 0.95, "persistence": 0.9, "detection_difficulty": 0.9},
            {"name": "定时任务后门", "stealth": 0.8, "persistence": 0.9, "detection_difficulty": 0.7},
            {"name": "服务后门", "stealth": 0.7, "persistence": 0.95, "detection_difficulty": 0.8},
            {"name": "内核模块后门", "stealth": 0.95, "persistence": 0.95, "detection_difficulty": 0.95}
        ]
        
        persistence_results = []
        successful_persistence = []
        
        # 在已控制的主机上部署持久化
        target_hosts = self.compromised_hosts[:5] if self.compromised_hosts else [host.ip_address for host in self.discovered_hosts[:3]]
        
        for host_ip in target_hosts:
            host = next((h for h in self.discovered_hosts if h.ip_address == host_ip), None)
            if not host:
                continue
            
            # 选择适合的持久化方法
            available_methods = persistence_methods.copy()
            if host.os_type == "Windows":
                # Windows环境下某些方法不适用
                available_methods = [m for m in available_methods if "内核模块" not in m["name"]]
            
            chosen_methods = random.sample(available_methods, random.randint(1, 3))
            
            for method in chosen_methods:
                success = random.random() < 0.8  # 80%成功率
                
                result = {
                    "host": host_ip,
                    "method": method["name"],
                    "success": success,
                    "stealth": method["stealth"],
                    "persistence": method["persistence"],
                    "detection_difficulty": method["detection_difficulty"],
                    "deployment_time": random.uniform(2.0, 15.0)
                }
                
                persistence_results.append(result)
                
                if success:
                    successful_persistence.append(result)
                    print(f"  ✅ {host_ip} 部署 {method['name']}: 成功")
                else:
                    print(f"  ❌ {host_ip} 部署 {method['name']}: 失败")
        
        # 计算统计信息
        success_rate = len(successful_persistence) / len(persistence_results) if persistence_results else 0
        avg_stealth = sum(p["stealth"] for p in persistence_results) / len(persistence_results) if persistence_results else 0
        avg_persistence = sum(p["persistence"] for p in successful_persistence) / len(successful_persistence) if successful_persistence else 0
        
        test_result = PenetrationTest(
            test_id="network_persistence_001",
            test_name="网络持久化测试",
            test_type=NetworkTestType.PERSISTENCE,
            target_network=self.target_network,
            discovered_hosts=self.discovered_hosts,
            successful_compromises=self.compromised_hosts,
            lateral_movements=[],
            data_exfiltrated={},
            persistence_methods=[p["method"] for p in successful_persistence],
            stealth_rating=avg_stealth,
            success_rate=success_rate,
            execution_time=sum(p["deployment_time"] for p in persistence_results),
            techniques_used=[p["method"] for p in persistence_results],
            recommendations=[
                "内核模块后门隐蔽性最高但部署复杂",
                "SSH后门简单有效且不易被发现",
                "DNS隧道后门适合长期潜伏",
                "多种方法组合使用提高持久性"
            ]
        )
        
        self.test_results.append(test_result)
        print(f"  📊 持久化成功率: {success_rate:.1%}, 部署 {len(successful_persistence)} 个后门")
        return test_result
    
    def run_all_tests(self) -> List[PenetrationTest]:
        """运行所有网络渗透测试"""
        print("🌐 开始网络渗透和横向移动场景测试...")
        print("=" * 60)
        
        # 按顺序运行测试
        self.test_network_discovery()
        self.test_service_enumeration()
        self.test_lateral_movement()
        self.test_privilege_escalation_network()
        self.test_data_exfiltration()
        self.test_network_persistence()
        
        # 计算总体统计
        total_tests = len(self.test_results)
        avg_success_rate = sum(test.success_rate for test in self.test_results) / total_tests
        avg_stealth = sum(test.stealth_rating for test in self.test_results) / total_tests
        total_execution_time = sum(test.execution_time for test in self.test_results)
        
        print("\n" + "=" * 60)
        print("📊 网络渗透测试总结:")
        print(f"  总测试数: {total_tests}")
        print(f"  平均成功率: {avg_success_rate:.1%}")
        print(f"  平均隐蔽性: {avg_stealth:.1%}")
        print(f"  总执行时间: {total_execution_time:.1f}秒")
        print(f"  发现主机: {len(self.discovered_hosts)}")
        print(f"  控制主机: {len(self.compromised_hosts)}")
        
        # 推荐最佳技术
        best_test = max(self.test_results, key=lambda x: x.success_rate * x.stealth_rating)
        print(f"  最佳技术: {best_test.test_name}")
        
        return self.test_results
    
    def generate_report(self) -> str:
        """生成网络渗透测试报告"""
        report_content = f"""# 网络渗透和横向移动场景测试报告

**目标网络**: {self.target_network}
**测试时间**: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
**测试数量**: {len(self.test_results)}

## 网络拓扑发现

**发现主机总数**: {len(self.discovered_hosts)}
**成功控制主机**: {len(self.compromised_hosts)}

### 主机清单
"""
        
        for host in self.discovered_hosts[:10]:  # 显示前10台主机
            report_content += f"""
- **{host.ip_address}** ({host.hostname})
  - 操作系统: {host.os_type}
  - 开放端口: {', '.join(map(str, host.open_ports))}
  - 访问级别: {host.access_level}
  - 漏洞: {', '.join(host.vulnerabilities[:2])}
"""
        
        report_content += "\n## 测试结果详情\n\n"
        
        for test in self.test_results:
            report_content += f"""### {test.test_name}
- **测试ID**: {test.test_id}
- **测试类型**: {test.test_type.value}
- **成功率**: {test.success_rate:.1%}
- **隐蔽性**: {test.stealth_rating:.1%}
- **执行时间**: {test.execution_time:.2f}s

**使用技术**:
{chr(10).join(f'- {technique}' for technique in test.techniques_used)}

**建议**:
{chr(10).join(f'- {rec}' for rec in test.recommendations)}

---

"""
        
        return report_content

def main():
    """主函数"""
    print("🌐 网络渗透和横向移动场景测试系统")
    print("=" * 40)
    
    # 创建测试器
    tester = NetworkPenetrationScenarios()
    
    # 运行所有测试
    results = tester.run_all_tests()
    
    # 生成报告
    report = tester.generate_report()
    
    # 保存报告
    report_file = f"network_penetration_report_{datetime.now().strftime('%Y%m%d_%H%M%S')}.md"
    with open(report_file, 'w', encoding='utf-8') as f:
        f.write(report)
    
    print(f"\n📋 报告已保存: {report_file}")

if __name__ == "__main__":
    main()